﻿<%@ WebHandler Language="C#" Class="CertificateWriter" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Web.SessionState;

public class CertificateWriter : IHttpHandler , IRequiresSessionState {
    
    public void ProcessRequest (HttpContext context) {
        
        
        
        context.Response.ContentType = "image/jpeg";

        if (context.Request["ID"] == null)
            return;

        string strID = context.Request["ID"];

        Image imNew = context.Session[strID] as Image;

        if (imNew == null)
            return;


        resizeImage(context,imNew, 850, 630);
        
        
        
        
        
    }
    
    
    
    /// <summary>
    /// this function will resize image and return the new one
    /// </summary>
    /// <param name="imNew">the image</param>
    /// <param name="w">the new width</param>
    /// <param name="h">the new height</param>
    /// <returns></returns>
    public static void resizeImage (HttpContext context, Image imNew,int w,int h)
    {
        System.Drawing.Bitmap bmOld = (Bitmap)imNew;

        int oldH = bmOld.Height;
        int oldW = bmOld.Width;


        int newH = 0;
        int newW = 0;

        newH = h;
        newW = newH * oldW / oldH;

        if (newW > w)
        {
            newW = w;
            newH = newW * oldH / oldW;
        }


        
        
        System.IO.MemoryStream ms1 = new System.IO.MemoryStream();

        bmOld.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);




        context.Response.ContentType = "image/jpeg";
        byte[] btNew1 = ms1.ToArray();
        context.Response.OutputStream.Write(btNew1, 0, btNew1.Length);

        return;
        
        


        Bitmap bmNew = new Bitmap(w, h);
        bmNew.SetResolution(bmOld.HorizontalResolution, bmOld.VerticalResolution);
        Graphics grdNew = Graphics.FromImage((Image)bmNew);

        grdNew.CompositingQuality = CompositingQuality.HighQuality;
        grdNew.InterpolationMode = InterpolationMode.HighQualityBicubic;
        grdNew.SmoothingMode = SmoothingMode.HighQuality;

        grdNew.FillRectangle(new SolidBrush(Color.FromName("white")), new Rectangle(0, 0, w, h));

        grdNew.DrawImage((Image)bmOld, new RectangleF(0 + ((w - newW) / 2), 0 + ((h - newH) / 2), newW, newH));



        grdNew.Dispose();


        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        bmNew.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);




        context.Response.ContentType = "image/jpeg";
        byte[] btNew = ms.ToArray();
        context.Response.OutputStream.Write(btNew, 0, btNew.Length);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}